package com.secf.service.action.hpy.hys.day87;

import java.sql.*;

/**
 * @Author bug菌
 * @Source 公众号：猿圈奇妙屋
 * @Date 2024年7月9日15:01:32
 */
public class TransactionTest {

    public static void main(String[] args) {
        // 数据库连接配置
        String url = "jdbc:mysql://localhost:3306/review_db";
        String username = "root";
        String password = "123456";

        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册JDBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            conn = DriverManager.getConnection(url, username, password);
            conn.setAutoCommit(false); // 开始事务

            // 创建Statement对象
            stmt = conn.createStatement();

            // 执行数据库查询操作
            String sql = "SELECT id, name, sex FROM user";
            ResultSet rs = stmt.executeQuery(sql);

            // 处理查询结果
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String sex = rs.getString("sex");
                // 打印结果
                System.out.println("id: " + id + ", name: " + name + ", sex: " + sex);
            }

            // 提交事务
            conn.commit();
            System.out.println("事务提交成功！");
        } catch (SQLException e) {
            try {
                if (conn != null) {
                    conn.rollback(); // 回滚事务
                }
                System.out.println("事务回滚成功！");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            close(stmt);
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 辅助方法，用于关闭ResultSet和Statement
    private static void close(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}